'use strict';
const dbHelper = require("db-helper")
const payUtil = require("pay-util")
const db = uniCloud.database()
const dbCmd = db.command
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('同步订单退款状态', event)
	let count = await dbHelper.getCount("t3ds-refund-apply", {
		status: "REFUNDING"
	})
	if (count === 0) {
		return;
	}
	console.log('退款中订单数：', count)
	let pageSize = 20;
	var pages = 1
	let platform = 'mp-weixin' //context.PLATFORM
	let uniPayInstance = payUtil.getPayInstance("wxpay", platform);
	let page = await dbHelper.getPage("t3ds-refund-apply", pages, pageSize, {
		status: 'REFUNDING'
	}, [{
		field: 'auditTime',
		order: "asc"
	}])
	for (let apply of page.list) {
		const transaction = await db.startTransaction();
		const applyCollection = transaction.collection("t3ds-refund-apply")
		const orderCollection = transaction.collection("t3ds-order")
		try{
			// let apply = page.list[i];
			let res = await uniPayInstance.refundQuery({
				outTradeNo: apply.orderSn
			})
			let refundItem = res.refundList[0];
			if (refundItem.refundStatus === "SUCCESS") {
				//退款成功
				await applyCollection.doc(apply._id).update({
					status: "REFUNDED",
					refundTime: refundItem.refundSuccessTime
				})
				if (apply.ticketIds && apply.ticketIds.length) {
					for (var i = 0; i < apply.ticketIds.length; i++) {
						let id = apply.ticketIds[i]
						await transaction.collection("t3ds-ticket-code").doc(id).update({
							status: -4
						})
					}
				}
				let order = await dbHelper.getById("t3ds-order", apply.orderSn)
				let refundTicketCount = await dbHelper.getCount("t3ds-ticket-code", {
					orderId: apply.orderSn,
					status: dbCmd.in([-3, -4])
				})
				if (refundTicketCount === order.items[0].count) {
					await dbHelper.update("t3ds-order", {
						_id: order._id,
						status: 8
					}, transaction)
				}
			} else if (refundItem.refundStatus === "CHANGE" || refundItem.refundStatus === "REFUNDCLOSE") {
				await applyCollection.doc(apply._id).update({
					status: "FAILED"
				})
				if (apply.ticketIds && apply.ticketIds.length) {
					for (var i = 0; i < apply.ticketIds.length; i++) {
						let id = apply.ticketIds[i]
						await transaction.collection("t3ds-ticket-code").doc(id).update({
							status: 0
						})
					}
				}
				await dbHelper.update("t3ds-order", {
					_id: apply.orderSn,
					status: 3
				}, transaction)
			}
			await transaction.commit();
			console.log('同步成功')
		}catch(e){
			console.log('同步出错', e)
			await transaction.rollback();
		}
	}
};
